package cn.tedu.springdemo.context;

import cn.tedu.springdemo.demo.DemoBean;
import cn.tedu.springdemo.demo.MyDemoBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * Spring 创建完成JavaBean，并且执行完成 set 注入以后， 会自动调用BeanPostProcessor
 * - 先调用方法 postProcessBeforeInitialization
 * - 在java Bean 初始化以后会自动调用 postProcessAfterInitialization
 * - 方法参数就是每一个Java Bean对象！
 */
@Component
@Service
public class BPPDemo implements BeanPostProcessor {
    Logger logger = LoggerFactory.getLogger(BPPDemo.class);
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //方法中不要返回null，要返回源对象本身！ 否则会影响Spring的工作！
        logger.debug("在Bean初始化之前{}", beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        logger.debug("在Bean初始化之后{}", beanName);
        //检查到 DemoBean 类型的对象就更换为 MyDemoBean类型的对象
        if (bean instanceof DemoBean){
            return new MyDemoBean();
        }
        return bean;
    }
}
